package com.scqkxx.gamebox.activity.myself;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SaveCallback;
import com.scqkxx.gamebox.R;
import com.scqkxx.gamebox.activity.activities.view.TitleView;
import com.scqkxx.gamebox.activity.myself.adapter.FeedBackAdapter;
import com.scqkxx.gamebox.databinding.ActivityFeedBackBinding;
import com.scqkxx.gamebox.utils.SaveLeanFileUtils;
import com.scqkzqtz.base.base.BaseActivity;
import com.scqkzqtz.base.library.utils.DrawableUtil;
import com.scqkzqtz.base.library.utils.ToastUtils;
//import com.scqkzqtz.takepictrue.TakePictrueUiils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;

/**
 * Created by zsx on 2018/8/9.
 * 意见反馈
 */

public class FeedBackActivity extends BaseActivity<ActivityFeedBackBinding> {
    public static final String imageCamera = "IMAGECAMERA";
    public static final int MAX_IMAGE_NUMBER = 6;//最多选择图片数量

    private List<String> imagePathList = new ArrayList<>();
    private List<String> imagePathList2 = new ArrayList<>();
    private List<String> imageUrlList = new ArrayList<>();
    private FeedBackAdapter adapter;

    @Override
    public int setLayoutId() {
        return R.layout.activity_feed_back;
    }

    @Override
    public void init() {
        imagePathList.add(imageCamera);
        initView();
    }

    private void initView() {
        binding.tvSubmit.setBackground(DrawableUtil.getSolidRectDrawable(6, Color.parseColor("#E7BD5D")));
        binding.tvSubmit.setOnClickListener(v -> onSubmit());
        binding.tvTitleView.setOnTitleClickListener(new TitleView.onTitleClickListener() {
            @Override
            public void onTitleClick(int mTitleType) {
                if (TitleView.CLICK_BACK == mTitleType) {
                    finish();
                }
            }
        });

        binding.recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        adapter = new FeedBackAdapter(this, imagePathList);
        binding.recyclerView.setAdapter(adapter);

        adapter.setOnClickDelectItem(new FeedBackAdapter.OnClicktItemListener() {
            @Override
            public void onDelectItem(int position, List<String> pathList) {
                imagePathList = pathList;
            }

            @Override
            public void onClickAddItem() {
//                new TakePictrueUiils()
//                        .setClip(false)
//                        .setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark))
//                        .setOnSelectTakePictrueListener(new TakePictrueUiils.OnSelectTakePictrueListener() {
//                            @Override
//                            public void onTakePictru(Bitmap bitmap, String pictrueFlie) {
//                                addImagePaths(pictrueFlie);
//                            }
//                        })
//                        .start(FeedBackActivity.this);
            }
        });
    }

    /**
     * 点击提交
     */
    private void onSubmit() {
        if (TextUtils.isEmpty(binding.etContent.getText().toString().trim())) {
            ToastUtils.showShortToast(this, "反馈内容不能为空！");
            return;
        }
        binding.tvSubmit.setEnabled(false);
        imagePathList2.clear();
        imagePathList2.addAll(imagePathList);
        imagePathList2.remove(imageCamera);
        if (imagePathList2.size() == 0) {
            send();
        } else {
            saveImage();
        }
    }

    /**
     * 保存图片到数据库
     */
    private void saveImage() {
        imageUrlList.clear();
        for (String imagePath : imagePathList2) {
            SaveLeanFileUtils.save("feedbackIamge", imagePath, new SaveLeanFileUtils.OnSaveInBackground() {
                @Override
                public void onSuccess(String url) {
                    imageUrlList.add(url);
                    if (imageUrlList.size() == imagePathList2.size()) {
                        send();
                    }
                }

                @Override
                public void onError(String e) {
                    removeDisposable();
                    binding.tvSubmit.setEnabled(true);
                }

                @Override
                public void onSubscribe(Disposable d) {
                    addDisposable(d);
                }
            });
        }
    }

    /**
     * 上传数据
     */
    private void send() {
        AVObject avObject = new AVObject("A_DxtFeedback");
        avObject.put("advice", binding.etContent.getText().toString().trim());
        if (imageUrlList.size() != 0)
            avObject.put("images", imageUrlList);
        if (AVUser.getCurrentUser() != null) {
            avObject.put("userId", AVUser.getCurrentUser().getObjectId());
            avObject.put("nickname", AVUser.getCurrentUser().getString("nickname"));
            avObject.put("headImageUrl", AVUser.getCurrentUser().getString("headImageUrl"));
        }
        avObject.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                binding.tvSubmit.setEnabled(true);
                if (e == null) {
                    ToastUtils.showShortToast(FeedBackActivity.this, "已提交");
                    FeedBackActivity.this.finish();
                }
            }
        });

    }


    private void addImagePaths(String imagePath) {
        imagePathList.remove(imageCamera);
        if (imagePathList.size() < MAX_IMAGE_NUMBER) imagePathList.add(imagePath);
        imagePathList.add(imageCamera);
        adapter.setImagePathList(imagePathList);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            //当isShouldHideInput(v, ev)为true时，表示的是点击输入框区域，则需要显示键盘，同时显示光标，反之，需要隐藏键盘、光标
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    //处理Editext的光标隐藏、显示逻辑
                    binding.etContent.clearFocus();
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
